package api

import (
	"FeedXmh/app/dao"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

var Utils = utils{}

type utils struct {
}

func (a *utils) GetHmum(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetQueryMap()
	farmid := gconv.String(params["farmid"])
	houseid := gconv.String(params["houseid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	sql := ""
	if houseid != "" {
		sql = fmt.Sprintf("SELECT DISTINCT(hnum) AS hnum FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr AS addr FROM t_device WHERE houseid=%s) order by hnum asc;", houseid)
	}
	if farmid != "" {
		sql = fmt.Sprintf("SELECT DISTINCT(hnum) AS hnum FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr AS addr FROM t_device WHERE houseid in (SELECT id as houseid FROM t_house WHERE farmid=%s)) order by hnum asc;;", farmid)
	}
	if hnum_prefix != "" {
		sql = fmt.Sprintf("SELECT DISTINCT(hnum) AS hnum FROM t_hzfgw_node_para WHERE hnum LIKE '%s%%' and addr in (SELECT device_addr AS addr FROM t_device WHERE houseid=%s) order by hnum asc;", hnum_prefix, houseid)
	}
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		records, err := db.GetAll(sql)
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["data"] = records.List()
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
